<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
    <el-form-item label="学年" prop="semester">
          <el-input
            v-model="queryParams.year"
            placeholder="请输入学年"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-input
            v-model="queryParams.semester"
            placeholder="请输入学期"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学生名称" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="成绩" prop="scoreNum">
            <el-input-number v-model="queryParams.scoreBeginNum" controls-position="right"   placeholder="请输入开始成绩" clearable></el-input-number>
            至
            <el-input-number v-model="queryParams.scoreEndNum" controls-position="right" placeholder="请输入结束成绩" clearable></el-input-number>
        </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学院名称" prop="collegeName">
        <el-input
          v-model="queryParams.collegeName"
          placeholder="请输入学院名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专业名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入专业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleSync"
          >学生信息导入</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:score:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:score:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:score:teacher']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport">导入</el-button>
          </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="scoreList"
    >
      <el-table-column label="学年" align="center" prop="year" />
      <el-table-column label="学期" align="center" prop="semester" />
      <el-table-column label="学生名称" align="center" prop="studentName" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="学院名称" align="center" prop="collegeName" />
      <el-table-column label="专业名称" align="center" prop="deptName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="分数" align="center" prop="scoreNum" />
      <!-- <el-table-column
        label="考试时间"
        align="center"
        prop="examTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.examTime }}</span>
        </template>
      </el-table-column> -->
      
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSetScore(scope.row)"
            >录入成绩</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:score:remove']"
            >删除</el-button> -->
          
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!-- 录入成绩对话框 -->
    <el-dialog title="成绩录入" :visible.sync="dialogFormVisible" width= "300px">
      <el-input v-model="scoreNum" placeholder="请输入成绩"></el-input>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="scoreSetConfrim()">确 定</el-button>
  </div>
</el-dialog>

 <!-- 导入对话框 -->
 <el-dialog :title="importUpload.title" :visible.sync="importUpload.open" width="400px" append-to-body>
      <el-upload
        ref="importUpload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="importUpload.headers"
        :action="importUpload.url + '?updateSupport=' + importUpload.updateSupport"
        :disabled="importUpload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="importUpload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
   

    <!-- 添加或修改成绩对话框，需要的话在index里面去粘贴 -->

  </div>
</template>

<script>
import {
  listScore,
  getScore,
  delScore,
  addScore,
  updateScore,
  listTeacherScore,
  syncStudent,
  editScore
} from "@/api/edu/score";
import { listCourse } from "@/api/edu/course";
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from "@/api/edu/student";
import { listClass } from "@/api/edu/class";
import {listTeacher, deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Score",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      teacherList:null,
      // 选中数组
      ids: [],
      time: [],
      selectedTeacher:null,
      dialogFormVisible:false, //成绩录入弹出框
      courseNameList:null,
      classNameList:null,
      currentTime: new Date().getFullYear(),
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      studentList:[],
      studentNames:null,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      StudentLoading:false,
      // 成绩表格数据
      scoreList: [],
      courseNames:"",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        studentName: null,
        courseId: null,
        courseName: null,
        teacherId: null,
        teacherName: null,
        deptId: null,
        deptName: null,
        year: null,
        semester: null,
        classId: null,
        className: null,
        scoreNum: null,
        scoreBeginNum: null,
        scoreEndNum: null,
        examTime: null,
        collegeId: null,
        collegeName: null,
      },
      //成绩录入对象
      scoreNum:'',
      scoreId:'',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseNameList: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" },
        ],
      },
      year:null,
      semester:null,
      importUpload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/edu/score/importData"
      }
    };
  },
  created() {
    this.getCurrentYear ()
    this.getList();
    // this.generateYears();
    // this.getCourse();
    // this.getDeptTree()
    // this.getClassList();
    
  },
  methods: {
       /**
     * 导入
     */
    // 提交上传文件
    submitFileForm() {
      this.$refs.importUpload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('edu/score/importTemplate', {
      }, `成绩_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.importUpload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.importUpload.open = false;
      this.importUpload.isUploading = false;
      this.$refs.importUpload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    handleImport(){
      this.importUpload.open = true;
    },
    //获取当前的年份和学期
    getCurrentYear () {
      this.getConfigKey("edu.current.year.semester").then(response => {
        console.log(response)
        let yearSemester = response.msg
        let yearSemesterArr = yearSemester.split("-")
        this.queryParams.year = Number(yearSemesterArr[0]);
        this.queryParams.semester = Number(yearSemesterArr[1]);
        this.year = Number(yearSemesterArr[0]);
        this.semester = Number(yearSemesterArr[1]);
      });
    },
    
    getClassList() {
      listClass(this.queryParams).then((response) => {
        this.classList = response.rows;
      });
    },
    //成绩录入确认框
    scoreSetConfrim(){
      editScore({scoreId:this.scoreId,scoreNum:this.scoreNum}).then(res =>{
        this.$modal.msgSuccess("录入成功");
        this.dialogFormVisible = false
        this.getList()
        
      })
    },
    //同步数据
    handleSync(){
      this.$modal.confirm('确认是否同步'+this.year+'-'+this.semester+'学期的学生信息').then(() =>{
        console.log("同步")
        syncStudent().then(res =>{
        this.getList()
        this.$modal.msgSuccess("同步完成");
      })
         }).then(() => {
            console.log("*******确认")
         }).catch(() => {
          console.log("*******取消")
         }); 
    },
    //成绩录入
    handleSetScore(row){
        this.dialogFormVisible = true
        this.scoreId = row.scoreId
        this.scoreNum = ''
    },
    StudentRemoteMethod (query) {
      var  a  = {
        phonenumber: null,
        sex: null,
        studentCode: null,
        userId: null,
        userName: null,
        deptId: null,
        deptName: null,
        nickName: null,
        email: null,
        idCard: null,
        avatar: null,
        classId: query,
        className: null,
        dateOfBirth: null,
        city: null,
        state: null,
        address: null,
        dateEnrolled: null,
        dateGraduated: null,
        gpa: null,
        minor: null,
        requireCredits: null,
        totalCredits: null,
        requireSecondCredits: null,
        totalSecondCredits: null,
        parentName: null,
        parentPhone: null,
        counsellorId: null,
        counsellorName: null,
        counsellorPhone: null,
        collegeId: null,
        collegeName: null,
     
      };
      listStudent(a).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
        
      });
   
    },

           //远程获取教师
      teacherListRemoteMethod(query){
 
      if(!this.teacherList){
        this.counsellorLoading = true
        listTeacher(query).then(res =>{
          console.log(res)
          this.teacherList = res.data
          this.counsellorLoading = false
        }).catch(err =>{
          console.log(err)
          this.$modal.msgError(err.message);
        })
      }
      
    },

    getCourse() {
      listCourse(this.queryParams).then((response) => {
        this.courseNames = response.rows;
      });
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    /** 查询成绩列表 */
    getList() {
      this.loading = true;
      listTeacherScore(this.queryParams).then((response) => {
        this.scoreList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.selectedTeacher  =  "",
      this.courseNameList = "",
      this.classNameList = "",
      this.studentNames = ""
    },
    // 表单重置
    reset() {
      this.form = {
        scoreId: null,
        studentId: null,
        studentName: null,
        courseId: null,
        courseName: null,
        teacherId: null,
        teacherName: null,
        deptId: null,
        deptName: null,
        year: null,
        semester: null,
        classId: null,
        className: null,
        scoreNum: null,
        examTime: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        collegeId: null,
        collegeName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.resetQueryParams()
      this.selectedTeacher  =  "",
      this.courseNameList = "",
      this.classNameList = ""
      this.studentNames = ""
      this.handleQuery();
    },
    resetQueryParams(){
      this.queryParams= {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        studentName: null,
        courseId: null,
        courseName: null,
        teacherId: null,
        teacherName: null,
        deptId: null,
        deptName: null,
        year: null,
        semester: null,
        classId: null,
        className: null,
        scoreNum: null,
        examTime: null,
        collegeId: null,
        collegeName: null,
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.scoreId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectedTeacher  =  "",
      this.courseNameList = "",
      this.classNameList = "",
      this.studentNames = "",
      this.open = true;
      this.title = "添加成绩";
      this.teacherListRemoteMethod("")

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.selectedTeacher  =  "",
      this.courseNameList = "",
      this.classNameList = "",
      this.studentNames = ""
      const scoreId = row.scoreId || this.ids;
      getScore(scoreId).then((response) => {
        this.form = response.data;
        this.selectedTeacher = response.data.teacherId,
        this.courseNameList = response.data.courseId,
        this.classNameList = response.data.classId,
        this.studentNames = response.data.studentId
        this.open = true;
        this.title = "修改成绩";

     
      });
      this.teacherListRemoteMethod("")
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.scoreId != null) {
            updateScore(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScore(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scoreIds = row.scoreId || this.ids;
      this.$modal
        .confirm('是否确认删除成绩编号为"' + scoreIds + '"的数据项？')
        .then(function () {
          return delScore(scoreIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "edu/score/export/teacher",
        {
          ...this.queryParams,
        },
        `score_${new Date().getTime()}.xlsx`
      );
    },
    generateYears() {
      const currentYear = new Date().getFullYear();
      for (let i = -4; i <= 0; i++) {
        this.time.push(currentYear + i);
      }
    },

  },
    watch: {
    selectedTeacher(value) {
      // 根据选中的教师ID值获取对应的教师名称
      const selectedTeacher = this.teacherList.find(item => item.userId === value);
      if (selectedTeacher) {
        // 将教师名称和ID值存储到表单中
        this.form.teacherName = selectedTeacher.nickName;
        this.form.teacherId = selectedTeacher.userId;
      }
    },
    courseNameList(value) {
      // 根据选中的课程ID值获取对应的教师名称
      console.log(value);
      console.log(this.courseNames);
      const courseNameList = this.courseNames.find(item => item.courseId === value);
      if (courseNameList) {
     
        this.form.courseId = courseNameList.courseId;
        this.form.courseName = courseNameList.name;
      }
    },
    classNameList(value) {
      // 根据选中的班级ID值获取对应的教师名称
      console.log(this.classList);
      const classNameList = this.classList.find(item => item.classId === value);
      if (classNameList) {
        // classList
        this.form.classId = classNameList.classId;
        this.form.className = classNameList.name;
      }
      console.log(this.form.classId);
      this.StudentRemoteMethod(this.form.classId)
    },

    
    studentNames(value) {
      // 根据选中的班级ID值获取对应的教师名称
      console.log(123);
      console.log(value);
      const studentNames = this.studentList.find(item => item.studentId === value);
      if (studentNames) {
        console.log(studentNames);
        // classList
        this.form.studentId = studentNames.studentId;
        this.form.studentName = studentNames.nickName;
      }

    },


  }
};
</script>